<template>
  <div id="edit-info-container">
    <MMNavBar
      :title="title"
      :rightText="rightText"
      :back="backUrl"
      @click-right="saveEdit"
    ></MMNavBar>
    <div class="main-container">
      <van-uploader
        v-if="$route.query.prop === 'avatar'"
        v-model="files"
        :after-read="afterRead"
        :max-count="1"
      />
      <van-field v-else v-model="value" placeholder="请输入" />
    </div>
  </div>
</template>

<script>
import MMNavBar from '@/components/MMNavBar'
import { mapMutations, mapGetters } from 'vuex'
import { editUserInfo, uploadAvatar } from '@/api/my'
export default {
  name: 'edit-info',
  data () {
    return {
      value: this.$store.state.userInfo[this.$route.query.prop],
      title: '修改昵称',
      backUrl: '/userInfo',
      files: [],
      rightText: undefined
    }
  },
  components: {
    MMNavBar
  },
  computed: {
    ...mapGetters(['avatarUrl'])
  },
  created () {
    const { prop, url } = this.$route.query
    const titleList = {
      nickname: '昵称',
      intro: '简介',
      position: '岗位',
      avatar: '头像'
    }
    this.title = '修改' + titleList[prop]
    this.value = this.$store.state.userInfo[prop]
    if (url) {
      this.backUrl = '/' + url
    }
    this.files[0] = {
      url: this.avatarUrl
    }
  },
  watch: {
    value (value) {
      this.rightText = '保存'
    }
  },
  methods: {
    ...mapMutations(['CHANGEPROP']),
    afterRead (data) {
      uploadAvatar(data.file).then(res => {
        console.log(res)
        this.value = res.data.data[0].id
      })
    },
    saveEdit () {
      this.$toast.loading('修改中...')
      const { prop, url } = this.$route.query
      const data = {
        [prop]: this.value
      }
      editUserInfo(data).then(res => {
        if (res.data.code === 200) {
          this.$toast.success('修改成功')
          let propValue = ''
          // 头像
          propValue = prop === 'avatar' ? res.data.data.avatar : this.value
          this.CHANGEPROP({
            propName: prop,
            propValue
          })
          // 判断返回my界面
          if (url) {
            return this.$router.replace(`/${url}`)
          }
          this.$router.replace('/userInfo')
        }
      })
    }
  }
}
</script>

<style lang="less">
#edit-info-container {
  background-color: @white-color;
  .main-container {
    padding-top: 20px;
    padding-left: 15px;
    padding-right: 15px;
    text-align: center;
    .van-field {
      background-color: @bg-color;
      padding: 0;
    }
  }
}
</style>
